<?php
Class cart extends Front_Controller {
 	function __construct(){
		parent::__construct();
	 	$this->load->helper("footer_page");
		date_default_timezone_set('Asia/Ho_Chi_Minh');
	}
	function index(){	
		$data["info_category"] = $this->db->get("categories")->result(); 
		
		$this->load->helper("handle_string_helper");
		$data['gift_cards_enabled'] 	= $this->gift_cards_enabled;
		$data['homepage']				= true;
		
		$data['products_banchay']		= $this->Product_model->get_homepage_products('active_banchay');
		$data['products_khuyendung']	= $this->Product_model->get_homepage_products('active_khuyendung');
		$data['products_chuluc']		= $this->Product_model->get_homepage_products('active_chuluc',12);
		
		$customer = $this->go_cart->customer();
		//print_r($customer);exit;
		if(!empty($customer)){
			if(!empty($data['products_banchay']))
				$data["price_products_banchay"]	 = $this->Product_model->get_price_user($data["products_banchay"],$customer["group_id"]);
			if(!empty($data['products_khuyendung']))
				$data["price_products_khuyendung"]	 = $this->Product_model->get_price_user($data["products_khuyendung"],$customer["group_id"]);
			if(!empty($data['products_chuluc']))
				$data["price_products_chuluc"]	 = $this->Product_model->get_price_user($data["products_chuluc"],$customer["group_id"]);
		}
		$data["meta_image"] = base_url("uploads/banners/banner-home-3.jpg");
		$this->view('homepage', $data);
	}
	function get_price_shipping(){ // lấy ra phí vận chuyển 
		$this->load->helper('formatting');
		$data['ship_locations']	= $this->Location_model->ship_location();
		$data["ship_locations"] = $this->Location_model->get_city_in_location($data['ship_locations']);
		$data['ship_weights']	= $this->Location_model->ship_weight();
		$data['ship_costs']		= $this->Location_model->ship_cost_frontend();	
		$data['page_title']		= sprintf(lang('zone_areas_for'), $data['zone']->name);
		$this->view('ship_cost',$data);
	}
	function page($id = false)
	{
		//if there is no page id provided redirect to the homepage.
		$data['page']	= $this->Page_model->get_page($id);
		
		if(!$data['page'])
		{
			show_404();
		}		
		
		if($data['page']->parent_id > 0){
			$data['page_parent']	= $this->Page_model->get_page($data['page']->parent_id);
		}
		
		$this->load->model('Page_model');
		$data['base_url']			= $this->uri->segment_array();
		
		$data['fb_like']			= true;

		$data['page_title']			= $data['page']->title;
		
		$data['meta']				= $data['page']->meta;
		$data['seo_title']			= (!empty($data['page']->seo_title))?$data['page']->seo_title:$data['page']->title;
		
		$data['gift_cards_enabled'] = $this->gift_cards_enabled;
		
		if(empty($data['page_parent']))
			$data['breadcrumb'] 		= array( '0'=>array('name'=>$data['page']->title,'url'=>'') );
		else
			$data['breadcrumb'] 		= array( '0'=>array('name'=>$data['page_parent']->title,'url'=>$data['page_parent']->slug),'1'=>array('name'=>$data['page']->title,'url'=>'') );
		
		if($data['page']->id == 11 || $data['page']->slug == 'cac-chinh-sach'){ //	Page cac chinh sach
			$data['page_child'] = $this->Page_model->get_pages(11);			
			$this->view('page_2', $data);
		}else{
			$this->view('page', $data);
		}
		
	}
	function search($code=false, $page = 0)
	{
		$this->load->model('Search_model');
		
		//check to see if we have a search term
		if(!$code)
		{
			//if the term is in post, save it to the db and give me a reference
			$term		= $this->input->post('term', true);
			$code		= $this->Search_model->record_term($term);
			
			// no code? redirect so we can have the code in place for the sorting.
			// I know this isn't the best way...
			redirect('cart/search/'.$code.'/'.$page);
		}
		else
		{
			//if we have the md5 string, get the term
			$term	= $this->Search_model->get_term($code);
		}
		
		if(empty($term))
		{
			//if there is still no search term throw an error
			$this->session->set_flashdata('error', lang('search_error'));
			redirect('cart');
		}

		$data['page_title']			= lang('search');
		$data['gift_cards_enabled']	= $this->gift_cards_enabled;
		
		//fix for the category view page.
		$data['base_url']			= array();
		
		$sort_array = array(
							'name/asc' => array('by' => 'name', 'sort'=>'ASC'),
							'name/desc' => array('by' => 'name', 'sort'=>'DESC'),
							'price/asc' => array('by' => 'sort_price', 'sort'=>'ASC'),
							'price/desc' => array('by' => 'sort_price', 'sort'=>'DESC'),
							);
		$sort_by	= array('by'=>false, 'sort'=>false);
	
		if(isset($_GET['by']))
		{
			if(isset($sort_array[$_GET['by']]))
			{
				$sort_by	= $sort_array[$_GET['by']];
			}
		}
		
			$data['page_title']	= lang('search');
			$data['gift_cards_enabled'] = $this->gift_cards_enabled;
		
			//set up pagination
			$this->load->library('pagination');
			$config['base_url']		= base_url().'cart/search/'.$code.'/';
			$config['uri_segment']	= 4;
			$config['per_page']		= 20;
			
			$config['first_link'] = 'First';
			$config['first_tag_open'] = '<li>';
			$config['first_tag_close'] = '</li>';
			$config['last_link'] = 'Last';
			$config['last_tag_open'] = '<li>';
			$config['last_tag_close'] = '</li>';

			$config['full_tag_open'] = '<div class="pagination"><ul>';
			$config['full_tag_close'] = '</ul></div>';
			$config['cur_tag_open'] = '<li class="active"><a href="#">';
			$config['cur_tag_close'] = '</a></li>';

			$config['num_tag_open'] = '<li>';
			$config['num_tag_close'] = '</li>';

			$config['prev_link'] = '&laquo;';
			$config['prev_tag_open'] = '<li>';
			$config['prev_tag_close'] = '</li>';

			$config['next_link'] = '&raquo;';
			$config['next_tag_open'] = '<li>';
			$config['next_tag_close'] = '</li>';
			
			$result					= $this->Product_model->search_products($term, $config['per_page'], $page, $sort_by['by'], $sort_by['sort']);
			$config['total_rows']	= $result['count'];
			$this->pagination->initialize($config);
			$customer = $this->go_cart->customer();
			$data['products']		= $result['products'];
			
			$data["price_user"]		= $this->Product_model->get_price_user($result["products"],$customer["group_id"]);
			
			foreach ($data['products'] as &$p)
			{
				$p->images	= (array)json_decode($p->images);
				$p->options	= $this->Option_model->get_product_options($p->id);
			}
			$this->view('category', $data);
	}
	
	function category($id)
	{
		
		//get the category
		$data['category'] = $this->Category_model->get_category($id);
		
		$data['category1'] = $this->Category_model->get_category_from_slug($this->uri->segment(1));
		
		
		
		if (!$data['category'] || $data['category']->enabled==0)
		{
			show_404();
		}
				
		$product_count = $this->Product_model->count_products($data['category']->id);
		$data['product_count'] = $product_count;
		//set up pagination
		$segments	= $this->uri->total_segments();
		$base_url	= $this->uri->segment_array();
		
		if($data['category']->slug == $base_url[count($base_url)])
		
		
		{
			$page	= 0;
			$segments++;
		}
		else
		{
			$page	= array_splice($base_url, -1, 1);
			$page	= $page[0];
		}
		
		$data['base_url']	= $base_url;
		$base_url			= implode('/', $base_url);
		
		$data['product_columns']	= $this->config->item('product_columns');
		$data['gift_cards_enabled'] = $this->gift_cards_enabled;
		
		$data['meta']		= (!empty($data['category']->meta))?$data['category']->meta:$data['category']->name;
		$data['page_title']	= (!empty($data['category']->seo_title))?$data['category']->seo_title:$data['category']->name;
		$data['keyword']	= (!empty($data['category']->keyword))?$data['category']->keyword:$data['category']->seo_title;
		
		$sort_array = array(
							'name/asc' => array('by' => 'products.name', 'sort'=>'ASC'),
							'name/desc' => array('by' => 'products.name', 'sort'=>'DESC'),
							'price/asc' => array('by' => 'sort_price', 'sort'=>'ASC'),
							'price/desc' => array('by' => 'sort_price', 'sort'=>'DESC'),
							);
		//$sort_by	= array('by'=>'priority', 'sort'=>'DESC');
		$sort_by	= array('by'=>'id', 'sort'=>'DESC');
		
		if(isset($_GET['by']))
		{
			if(isset($sort_array[$_GET['by']]))
			{
				$sort_by	= $sort_array[$_GET['by']];
			}
		}
		
		//set up pagination
		$this->load->library('pagination');
		$config['base_url']		= site_url($base_url);
		$config['uri_segment']	= $segments;
		$config['per_page']		= 24;
		$config['total_rows']	= $product_count;
		
		$config['first_link'] = '&laquo;&laquo;';
		$config['first_tag_open'] = '<li>';
		$config['first_tag_close'] = '</li>';
		$config['last_link'] = '&raquo;&raquo;';
		$config['last_tag_open'] = '<li>';
		$config['last_tag_close'] = '</li>';

		$config['full_tag_open'] = '<div class="col-xs-12 col-sm-6 col-md-6"><div class="pagination_wp"><ul class="pagination">';
		$config['full_tag_close'] = '</ul></div></div>';
		$config['cur_tag_open'] = '<li class="active"><a href="">';
		$config['cur_tag_close'] = '</a></li>';
		
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		
		$config['prev_link'] = '&laquo;';
		$config['prev_tag_open'] = '<li>';
		$config['prev_tag_close'] = '</li>';

		$config['next_link'] = '&raquo;';
		$config['next_tag_open'] = '<li>';
		$config['next_tag_close'] = '</li>';
				
		$this->pagination->initialize($config);
		
		$customer = $this->go_cart->customer();
		$id_category = $data['category']->id;
		$limit = $config['per_page'];
		if($id_category == 34){
			$this->load->model("category_model");
			$data["category_gift"] = $category 	 = $this->category_model->get_child_category($id_category);	
			$id_category = array(34);
			if(!empty($category)){
				foreach($category as $item){
					$id_category[] = $item->id; 	
				}	
			}
			$page = false;
			$limit = false;
			$data["list_category_product"] = $this->category_model->get_category_id_product($id_category);
		}
		$data['products']	= $this->Product_model->get_products($id_category,$limit, $page, $sort_by['by'], $sort_by['sort'],$customer);
		$data["price_user"] = $this->Product_model->get_price_user($data["products"],$customer["group_id"]);
		foreach ($data['products'] as &$p){
			$p->images	= (array)json_decode($p->images);
			$p->options	= $this->Option_model->get_product_options($p->id);
		}
		if($data['category']->name != $data['category1']->name)	
			$data['breadcrumb'] 		= array('0'=>array('name'=>$data['category1']->name,'url'=>site_url($this->uri->segment(1))) ,'1'=>array('name'=>$data['category']->name,'url'=>'') );
		else{
			$data['breadcrumb'] 		= array('0'=>array('name'=>$data['category']->name,'url'=>'') );
		}
		if(!empty($data["category_gift"]))
			$this->view('category_gif', $data);
		else
			$this->view('category', $data);
	}
	function get_comment_pro($id_pro,$page=0){
	
		$this->load->helper("pagging");
		$this->load->model("comment_model","cmt_m");
		$comment 		 = $this->cmt_m->get_cmt($id_pro,$page,6);
		$data["comment"] = $comment["result"];
		$data["id_product"] = $id_pro;
		$data["paging"]  = get_pagging(site_url("cart/get_comment_pro/".$id_pro."/"),4,6,$comment["total_row"]);
		$this->load->view("ajax/pro_cmt",$data);
	}
	function product($id){
		//get the product
		$this->load->helper("MY_url");
		$this->load->helper("pagging");
		$data['product']	= $this->Product_model->get_product($id);
		//echo '<pre>';print_r($data['product']);exit;
		if(!$data['product'] || $data['product']->enabled==0){
			show_404();
		}
		$data['category'] = $this->Category_model->get_category_from_slug($this->uri->segment(1));
		$data['category2'] = $this->Category_model->get_category_from_slug($this->uri->segment(2));	
		
		if (!$data['category'] || $data['category']->enabled==0){
			$data['category'] = '';
			$product_count = NULL;
		}else{				
			$product_count = $this->Product_model->count_products($data['category']->id);			
		}
		
		$data['product_count'] = $product_count;
		
		$data['base_url']			= $this->uri->segment_array();
		// load the digital language stuff
		$this->lang->load('digital_product');
		
		$data['options']	= $this->Option_model->get_product_options($data['product']->id);
		
		$related			= $data['product']->related_products;
		$data['related']	= array();
		
		$data['posted_options']	= $this->session->flashdata('option_values');
		$data['page_title']			= (!empty($data['product']->seo_title))?$data['product']->seo_title:$data['product']->name;
		$data['meta']				= (!empty($data['product']->meta))?$data['product']->meta:$data['page_title'];
		$data['keyword']			= (!empty($data['product']->keyword))?$data['product']->keyword:$data['page_title'];
		
		if($data['product']->images == 'false'){
			$data['product']->images = $images = array();
		}
		else{
			$data['product']->images	= $images = array_values((array)json_decode($data['product']->images));
		}
		
		$data['meta_image'] 			= base_url('uploads/images/medium/'.$images[0]->filename);
		$data['gift_cards_enabled'] 	= $this->gift_cards_enabled;
		//echo $this->uri->segment(1);exit;
		if(!empty($data['category2']))
			$data['breadcrumb'] 			= array( '0'=>array('name'=>$data['category']->name,'url'=>site_url($this->uri->segment(1))),'1'=>array('name'=>$data['category2']->name,'url'=>site_url($this->uri->segment(1)."/".$this->uri->segment(2))),'2'=>array('name'=>$data['product']->name,'url'=>'') );
		else
			$data['breadcrumb'] 			= array( '0'=>array('name'=>$data['category']->name,'url'=>site_url($this->uri->segment(1))),'1'=>array('name'=>$data['product']->name,'url'=>'') );
		$data["blogs"] = $this->Product_model->get_blogs($data['product']->id,4);
		$this->load->model("comment_model","cmt_m");
		$comment 	 	 = $this->cmt_m->get_cmt($data['product']->id);
		$data["comment"] = $comment["result"]; 
		$data["paging"]	 = get_pagging(site_url("cart/get_comment_pro/".$data['product']->id."/"),4,6,$comment["total_row"]);
		$data["id_product"] = $data['product']->id;
		$data["count_cmt"]  = $comment["total_row"];
		$data["city"]		= $this->Product_model->get_city();
		$data["zone_area"]	= $this->Product_model->get_zone_area(3780);
		$this->view('product', $data);
	}

	function tests(){
		$this->load->helper('create_captcha');
		echo get_captcha();	
		echo 'aa';exit;
	}

	function get_zone_area($id_city){
		$zone_area	= $this->Product_model->get_zone_area($id_city);
		echo "<option value=''>-- Quận/Huyện --</option>";
		
		foreach($zone_area as $item){
			echo '<option value="'.$item->id.'">'.$item->code.'</option>';	
		}
		exit;
	}

	function add_comment($obj_id){
		$post = $this->input->post();
		if(!empty($post)){
			$error = "";
			$email = $post["email"];
			if(!empty($email)){
				if (!filter_var($email,FILTER_VALIDATE_EMAIL)) {
				  $error .= "<p class='error'> Email không đúng định dạng </p>"; 
				}		
			}
			else{
				$error .= "<p class='error'> Vui lòng nhập email </p>";	
			}
			if(strtoupper($post["code"]) != $this->session->userdata("info_captcha")){
				$error .= "<p class='error'> Mã xác nhận không đúng </p>";
			}
			if(empty($post["fullname"]))
				 $error .= "<p class='error'> Vui lòng nhập họ tên </p>";
			if(empty($post["birth"]))
				 $error .= "<p class='error'> Vui lòng nhập ngày sinh </p>";
			if(!empty($error)){
				 echo json_encode(array("error"=>1,"mess"=>$error));exit;
			}else{
				 $info_user_comment = $this->info_user_comment($post);
				 $insert["customer_id"] = $info_user_comment["id_customer"];
				 $insert["table"] 		= $info_user_comment["obj_table"];
				 $insert["status"]		= 1;
				 $insert["score"]		= $post["score_star"];
				 $insert["content"]		= $post["content"];
				 $insert["obj_id"]		= $obj_id;
				 $insert["created"]     = time(); 
				 $this->db->insert("comment",$insert);
				 $product = $this->Product_model->get_detail($obj_id);
				 
				 // send mail
				 $this->load->helper("email");
				 $mess = "<p> ".$post["fullname"]." đã comment </p> <p>".$post["content"]."</p> <p> Đã comment sản phẩm: <a href='".site_url($product->slug)."'>".site_url($product->slug)."</a></p> <p>Quản lý comment: <a href='".site_url("admin/products/form/".$product->id)."'> ".site_url("admin/products/form/".$product->id)." </a></p>";
				 //$email = $this->config->item("email");
				 $email = "bbvothuy@gmail.com";
				 send_mail("Mail comment Plus Mainichi",$email,$mess,1);
				 echo json_encode(array("error"=>0,"mess"=>"Cảm ơn bạn đã đánh giá sản phẩm Plus Mainichi","time"=>date("d-m-Y h:i",$insert["created"]),"name"=>$post["fullname"],"content"=>$post["content"],"score"=>$post["score_star"]));exit;
			}
		}
	}
	function get_capcha(){
		$this->load->helper("create_captcha");
		echo get_captcha();
	}
	function info_user_comment($post){
		if(!empty($this->customer))
			return array("id_customer"=>$this->customer["id"],"obj_table"=>"customers");
		else{
			$info = $this->db->where("email",$post["email"])->get("email_receive_news")->row();
			if(!empty($info))
				return array("id_customer"=>$info->id,"obj_table"=>"email_receive_news");
			else{
				$info_customer = $this->db->where("email",$post["email"])->get("customers")->row();
				if(!empty($info_customer)){
					return array("id_customer"=>$info_customer->id,"obj_table"=>"customers");
				}
				else{
					$birth = explode("/",$post["birth"]);
					$birth = $birth[2]."-".$birth[1]."-".$birth[0];
					$this->db->insert("email_receive_news",array(
									"email"			=>$post["email"],
									"name"			=>$post["fullname"],
									"created"		=>time(),
									"code_active"	=>md5($post["email"]),
									"group_id"		=>1,
									"status"		=>'1',
									"obj_type"		=>1,
									'birth'			=>strtotime($birth),
									'gender' 		=>$post["gender"],
									'zone_id'		=> $post["city"],
									'zone_area_id'	=> $post["zone_area"],
								));
					
					return array("id_customer"=>$this->db->insert_id(),"obj_table"=>"email_receive_news");	
				}
			}
		}
	}
	function add_to_cart(){
		// Get our inputs
		$product_id		= $this->input->post('id');
		$quantity 		= $this->input->post('quantity');
		$post_options 	= $this->input->post('option');
		$price_user_option = "";
		// Get a cart-ready product array
		$product 	 = $this->Product_model->get_cart_ready_product($product_id, $quantity);
		$cusomter 	 = $this->go_cart->customer();
		if(!empty($cusomter)){
			$price_user  = $this->Product_model->get_price_user($product,$cusomter["group_id"]);
			$list_price_unset = array("saleprice","agencyprice","saleagencyprice");
			if(!empty($price_user)){
				foreach($list_price_unset as $index=>$value){
					$product[$value] = 0;
				}
				foreach($price_user as $index =>$val){
					$product["base_price"]=$product["price"] = $val;
				}
				$price_user_option = "active";
			}
		}		
		//if out of stock purchase is disabled, check to make sure there is inventory to support the cart.
		if(!$this->config->item('allow_os_purchase') && (bool)$product['track_stock'])
		{
			$stock	= $this->Product_model->get_product($product_id);
			//loop through the products in the cart and make sure we don't have this in there already. If we do get those quantities as well
			$items		= $this->go_cart->contents();
			$qty_count	= $quantity;
			foreach($items as $item)
			{
				if(intval($item['id']) == intval($product_id))
				{
					$qty_count = $qty_count + $item['quantity'];
				}
			}
			if($stock->quantity < $qty_count)
			{
				//we don't have this much in stock
				$this->session->set_flashdata('error', sprintf(lang('not_enough_stock'), $stock->name, $stock->quantity));
				$this->session->set_flashdata('quantity', $quantity);
				$this->session->set_flashdata('option_values', $post_options);

				redirect($this->Product_model->get_slug($product_id));
			}
		}

		// Validate Options 
		// this returns a status array, with product item array automatically modified and options added
		//  Warning: this method receives the product by reference
		$status = $this->Option_model->validate_product_options($product, $post_options);
		
		// don't add the product if we are missing required option values
		if( ! $status['validated'])
		{
			$this->session->set_flashdata('quantity', $quantity);
			$this->session->set_flashdata('error', $status['message']);
			$this->session->set_flashdata('option_values', $post_options);
		
			redirect($this->Product_model->get_slug($product_id));
		
		} else {
		
			//Add the original option vars to the array so we can edit it later
			$product['post_options']	= $post_options;
			
			//is giftcard
			$product['is_gc']			= false;
			
			// Add the product item to the cart, also updates coupon discounts automatically
			
			$this->go_cart->insert($product,$price_user_option);
			$this->go_cart->change_score_item(); // thay diem sổ 
			// go go gadget cart!
			
			redirect('cart/view_cart');
		}
	}
	
	function view_cart(){
		$data['page_title']			= 'View Cart';
		$data['gift_cards_enabled'] = $this->gift_cards_enabled;
		$data["shipping_location"]  = $this->go_cart->shipping_location();
		$data["order_weight"]		= $this->go_cart->order_weight();
		$data["customer"] 			= $this->go_cart->customer(); // thông tin user đang đăng nhập
		$data["checkout_cart"]		= $this->checkout_cart();	
		$data["score_user"] 		= $this->go_cart->_get_score_price_customer();
		$this->view('view_cart', $data);
	}
	
	function remove_item($key){
		//drop quantity to 0
		$this->go_cart->update_cart(array($key=>0));
		//cart_contents
		redirect('cart/view_cart');
	}
	
	function update_cart($redirect = false){
		//if redirect isn't provided in the URL check for it in a form field
		if(!$redirect) $redirect = $this->input->post('redirect');
		// see if we have an update for the cart
		$item_keys			= $this->input->post('cartkey');
		$coupon_code		= $this->input->post('coupon_code');
		$gc_code			= $this->input->post('gc_code');
		$gc_active_score	= $this->input->post('gc_active_score');
	
		$get_score_use		= $this->go_cart->_get_score_price_customer();
		$score_now = 0;	
		if(!empty($gc_active_score) and $get_score_use["score"] > 0){
			$customer = $this->go_cart->customer();				
			$info_cusomter   = $this->db->select("score")->where("id",$customer["id"])->get("customers")->row();			
			$order_cusomter  = $this->db->select("SUM(score_minus) as total_score_minus")->where("id",$customer["id"])->where("status <>","Delivered")->where("status <>","Cancelled")->get("orders")->row(); 
			if(!empty($order_cusomter))
				$score_now 		 = $info_cusomter->score - $order_cusomter->total_score_minus;
			else
				$score_now 		 = $info_cusomter->score;
		}
		if($coupon_code)
		{
			$coupon_code = strtolower($coupon_code);
		}
		//get the items in the cart and test their quantities
		$items			= $this->go_cart->contents();
		$new_key_list	= array();
		//first find out if we're deleting any products
		foreach($item_keys as $key=>$quantity){
			if(intval($quantity) === 0){
				//this item is being removed we can remove it before processing quantities.
				//this will ensure that any items out of order will not throw errors based on the incorrect values of another item in the cart
				$this->go_cart->update_cart(array($key=>$quantity),false,false,$score_now);
			}
			else{
				//create a new list of relevant items
				$new_key_list[$key]	= $quantity;
			}
		}
		$response	= array();
		foreach($new_key_list as $key=>$quantity){
			$product	= $this->go_cart->item($key);
			//if out of stock purchase is disabled, check to make sure there is inventory to support the cart.
			if(!$this->config->item('allow_os_purchase') && (bool)$product['track_stock'])
			{
				$stock	= $this->Product_model->get_product($product['id']);
				//loop through the new quantities and tabluate any products with the same product id
				$qty_count	= $quantity;
				foreach($new_key_list as $item_key=>$item_quantity)
				{
					if($key != $item_key)
					{
						$item	= $this->go_cart->item($item_key);
						//look for other instances of the same product (this can occur if they have different options) and tabulate the total quantity
						if($item['id'] == $stock->id)
						{
							$qty_count = $qty_count + $item_quantity;
						}
					}
				}
				if($stock->quantity < $qty_count)
				{
					if(isset($response['error']))
					{
						$response['error'] .= '<p>'.sprintf(lang('not_enough_stock'), $stock->name, $stock->quantity).'</p>';
					}
					else
					{
						$response['error'] = '<p>'.sprintf(lang('not_enough_stock'), $stock->name, $stock->quantity).'</p>';
					}
				}
				else
				{
					//this one works, we can update it!
					//don't update the coupons yet
					$this->go_cart->update_cart(array($key=>$quantity),false,false,$score_now);
				}
			}
			else
			{
				$this->go_cart->update_cart(array($key=>$quantity),false,false,$score_now);
			}
		}
		
		//if we don't have a quantity error, run the update
		if(!isset($response['error'])){
			//update the coupons and gift card code
			$response = $this->go_cart->update_cart(false, $coupon_code,$gc_code,$score_now);
			// set any messages that need to be displayed
		}else{
		
			$response['error'] = '<p>'.lang('error_updating_cart').'</p>'.$response['error'];
		}
		//check for errors again, there could have been a new error from the update cart function
		if(isset($response['error']))
		{
			$this->session->set_flashdata('error', $response['error']);
		}
		if(isset($response['message']))
		{
			$this->session->set_flashdata('message', $response['message']);
		}
		if($redirect)
		{
			redirect($redirect);
		}
		else
		{
			redirect('cart/view_cart');
		}
	}
	/***********************************************************
			Gift Cards
			 - this function handles adding gift cards to the cart
	***********************************************************/
	function giftcard(){
		if(!$this->gift_cards_enabled) redirect('/');
		// Load giftcard settings
		$gc_settings = $this->Settings_model->get_settings("gift_cards");
				
		$this->load->library('form_validation');
		
		$data['allow_custom_amount']	= (bool) $gc_settings['allow_custom_amount'];
		$data['preset_values']			= explode(",",$gc_settings['predefined_card_amounts']);
		
		if($data['allow_custom_amount'])
		{
			$this->form_validation->set_rules('custom_amount', 'lang:custom_amount', 'numeric');
		}
		
		$this->form_validation->set_rules('amount', 'lang:amount', 'required');
		$this->form_validation->set_rules('preset_amount', 'lang:preset_amount', 'numeric');
		$this->form_validation->set_rules('gc_to_name', 'lang:recipient_name', 'trim|required');
		$this->form_validation->set_rules('gc_to_email', 'lang:recipient_email', 'trim|required|valid_email');
		$this->form_validation->set_rules('gc_from', 'lang:sender_email', 'trim|required');
		$this->form_validation->set_rules('message', 'lang:custom_greeting', 'trim|required');
		
		if ($this->form_validation->run() == FALSE)
		{
			$data['error']				= validation_errors();
			$data['page_title']			= lang('giftcard');
			$data['gift_cards_enabled']	= $this->gift_cards_enabled;
			$this->view('giftcards', $data);
		}
		else
		{
			// add to cart
			$card['price'] = set_value(set_value('amount'));
			$card['id']				= -1; // just a placeholder
			$card['sku']			= lang('giftcard');
			$card['base_price']		= $card['price']; // price gets modified by options, show the baseline still...
			$card['name']			= lang('giftcard');
			$card['code']			= generate_code(); // from the string helper
			$card['excerpt']		= sprintf(lang('giftcard_excerpt'), set_value('gc_to_name'));
			$card['weight']			= 0;
			$card['quantity']		= 1;
			$card['shippable']		= false;
			$card['taxable']		= 0;
			$card['fixed_quantity'] = true;
			$card['is_gc']			= true; // !Important
			$card['track_stock']	= false; // !Imporortant
			$card['gc_info'] = array("to_name"	=> set_value('gc_to_name'),
									 "to_email"	=> set_value('gc_to_email'),
									 "from"		=> set_value('gc_from'),
									 "personal_message"	=> set_value('message')
									 );
			// add the card data like a product
			$this->go_cart->insert($card);
			redirect('cart/view_cart');
		}
	}
	public function view_detail_order($id_order){
		if(!empty($id_order)){
			$this->lang->load('common');
			$this->load->model("order_model");
			$data["order"]  = $this->order_model->get_order($id_order,1);
			$data["cart"]   = $this->order_model->get_items($id_order);
			foreach($data["cart"] as $item){
				$list_id[] = $item["id"];	
			}
			$data["category_name"] = $this->order_model->get_category_name($list_id);
			$this->partial('order_detail', $data);
		}
	}
	function checkout_cart(){
		$this->load->model("order_model");
		$id_customer = $this->customer["id"];
		$info_order  = $this->order_model->get_count_order($id_customer);
		if(!empty($info_order) and $info_order->totalorder >= 1)
			return 1;
		return 0;
	}
}